/*!
 * jQuery Sina Emotion v2.1.0
 *
 * Copyright 2012-2014 Lanfei
 * Released under the MIT license
 *
 * Date: 2014-05-19T20:10:23+0800
 */
(function($) {

	var $target;
	
	var $editor;

	var options;

	var emotions;

	var categories;

	var emotionsMap;

	var parsingArray = [];

	var customEmojiData = [];

	var defCategory = '默认';

	var emojiCategory = '自定义表情';

	var download;

	var wechatRegx = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::\\$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O"
		+ "|/::\\(|/::\\+|\\[囧\\]|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f"
		+ "|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)"
		+ "|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb"
		+ "|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn"
		+ "|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj"
		+ "|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip"
		+ "|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>"
		+  "||||||||||||||||||||"
		+ "|\\[嘿哈\\]|\\[捂脸\\]|\\[奸笑\\]|\\[机智\\]|\\[皱眉\\]|\\[耶\\]|\\[茶\\]|\\[红包\\]|\\[蜡烛\\]|/:--b|\\[Chick\\]"
		+ "|\\[Facepalm\\]";

	var specialRegx = '|||||||||||||||||||||[囧]|[嘿哈]|[捂脸]|[奸笑]|[机智]|[皱眉]|[耶]|[茶]|[红包]|[蜡烛]|[Facepalm]'
		+ '|[茶]|[Chick]';
	
	var initEvents = function() {
		$('body').bind({
			click: function() {
				$('#wechatEmotion').hide();
			}
		});

		$('#wechatEmotion').bind({
			click: function(event) {
				event.stopPropagation();
			}
		}).delegate('.prev', {
			click: function(event) {
				var page = $('#wechatEmotion .categories').data('page');
				showCatPage(page - 1);
				event.preventDefault();
			}
		}).delegate('.next', {
			click: function(event) {
				var page = $('#wechatEmotion .categories').data('page');
				showCatPage(page + 1);
				event.preventDefault();
			}
		}).delegate('.category', {
			click: function(event) {
				$('#wechatEmotion .categories .current').removeClass('current');
				showCategory($.trim($(this).addClass('current').text()));
				event.preventDefault();
			}
		}).delegate('.page', {
			click: function(event) {
				$('#wechatEmotion .pages .current').removeClass('current');
				var page = parseInt($(this).addClass('current').text() - 1);
				showFacePage(page);
				event.preventDefault();
			}
		}).delegate('.face', {
			click: function(event) {
				event.preventDefault();
				$('#wechatEmotion').hide();
				$img = $(this).children('img');
				if($img.attr("alt").indexOf("jxdevs") < 0){
					if ($editor) {
						$target.insertWechatEditor($(this).children('img').prop('alt'));
					} else {
						$target.insertTextWechat($(this).children('img').prop('alt'));
					}
				}else{
					var param = {};
					param.emojiLink = $img.attr("src").replace(download,"");
					param.id = $img.attr("id");
					param.bucket = 2;
					$.ajax({
					    url: "/customEmoji/sendEmoji",
					    data: param,
					    dataType:"json",
					    type:"POST",
					    success: function(res) {
					    	if(res){
					    		sendCustomEmoji(res);
					    	}
					    }
					});
				}
			}
		});
	};

	

	var loadEmotions = function(callback) {
		
		if(emotions){
			callback && callback();
			return;
		}

		if (!options) {
			options = $.fn.wechatEmotion.options;
		}

		emotions = {};
		categories = [];
		emotionsMap = {};

		$('body').append('<div id="wechatEmotion">正在加载，请稍后...</div>');

		initEvents();

		// 初始化缓存，页面仅仅加载一次就可以了
		(function(jQuery, customEmojiData) {

		var def = "默认";
		var custom = "自定义表情";

		var item;
		var emotionPicData = [
		      ['/::\)',100],['/::~',101],['/::B',102],['/::|',103],['/:8-)',104],
		      ['/::<',105],['/::$',106],['/::X',107],['/::Z',108],["/::'(",109],
		      ['/::-|',110],['/::@',111],['/::P',112],['/::D',113],['/::O',114],
		      ['/::(',115],['/::+',116],['[囧]',117],['/::Q',118],['/::T',119],
		      ['/:,@P',120],['/:,@-D',121],['/::d',122],['/:,@o',123],['/::g',124],
		      ['/:|-)',125],['/::!',126],['/::L',127],['/::>',128],['/::,@',129],
		      ['/:,@f',130],['/::-S',131],['/:?',132],['/:,@x',133],['/:,@@',134],
		      ['/::8',135],['/:,@!',136],['/:!!!',137],['/:xx',138],['/:bye',139],
		      ['/:wipe',140],['/:dig',141],['/:handclap',142],['/:&-(',143],['/:B-)',144],
		      ['/:<@',145],['/:@>',146],['/::-O',147],['/:>-|',148],['/:P-(',149],
		      ["/::'|",150],['/:X-)',151],['/::*',152],['/:@x',153],['/:8*',154],
		      ['/:pd',155],['/:<W>',156],['/:beer',157],['/:basketb',158],['/:oo',159],
		      ['/:coffee',160],['/:eat',161],['/:pig',162],['/:rose',163],['/:fade',164],
		      ['/:showlove',165],['/:heart',166],['/:break',167],['/:cake',168],['/:li',169],
		      ['/:bome',170],['/:kn',171],['/:footb',172],['/:ladybug',173],['/:shit',174],
		      ['/:moon',175],['/:sun',176],['/:gift',177],['/:hug',178],['/:strong',179],
		      ['/:weak',180],['/:share',181],['/:v',182],['/:@)',183],['/:jj',184],
		      ['/:@@',185],['/:bad',186],['/:lvu',187],['/:no',188],['/:ok',189],
		      ['/:love',190],['/:<L>',191],['/:jump',192],['/:shake',193],['/:<O>',194],
		      ['/:circle',195],['/:kotow',196],['/:turn',197],['/:skip',198],['/:oY',199],
		      ["",200],['',201],['',202],['',203],['',204],
		      ['',205],['',206],['',207],['',208],['',209],
		      ['',210],['[嘿哈]', 220],['[捂脸]', 223],['[奸笑]',222],
		      ['[机智]',221],['[皱眉]', 228],['[耶]', 224],['',211],
		      ['',212],['',213],['',214],
		      ['',215],['',216],['',217],['',218],['',219],
		      ['[茶]',227], ['[红包]',226], ['[蜡烛]',225],['[Chick]',229],['[Facepalm]', 223]
		];
		 
			for (var i = 0; i < emotionPicData.length; i++) {
				smileyArr=emotionPicData[i];
				var name=smileyArr[0];
				var icon = '';
				if (smileyArr[1] >= 200) {
					icon = '../plugins/wechat-emotion/image/' + smileyArr[1] + '.png';
				} else {
					icon= '../plugins/wechat-emotion/image/' + smileyArr[1] + '.gif';
				}
		        
				if (!emotions[def]) {
					emotions[def] = [];
					categories.push(def);
				}
		        
		        emotions[def].push( {
		        	phrase : name,
	            	name : name,
	            	icon : icon
	            });
		        
	            emotionsMap[name] =icon;
			}
			// 兼容显示旧版微信
			emotionsMap['/:--b'] = '../plugins/wechat-emotion/image/117.gif';


			for (var i = 0; i < customEmojiData.length; i++) {
				var tmp = customEmojiData[i];
				var link = tmp[0];
				var id = tmp[1];
				var bucket = tmp[2];

				if (!emotions[custom]) {
					emotions[custom] = [];
					categories.push(custom);
				}
		        
		        emotions[custom].push( {
		        	phrase : bucket,
	            	name : id,
	            	icon : link
	            });
		        
	            emotionsMap[id] =icon;
			}

		$('#wechatEmotion').html('<div class="right">'+
				'</div><ul class="categories"></ul><ul class="faces"></ul><ul class="pages"></ul>');

		$(parsingArray).parseWechat();
		parsingArray = null;

		callback && callback();
	
		})(jQuery, customEmojiData);
		
		 
	};

	var showCatPage = function(page) {

		var html = '';
		var length = categories.length;
		var maxPage = Math.ceil(length / 5);
		var $categories = $('#wechatEmotion .categories');
		var category = $categories.data('category') || defCategory;

		page = (page + maxPage) % maxPage;

		for (var i = page * 5; i < length && i < (page + 1) * 5; ++i) {
			html += '<li class="item"><a href="#" class="category' + (category == categories[i] ? ' current' : '') + '">' + categories[i] + '</a></li>';
		}

		$categories.data('page', page).html(html);
	};

	var showCategory = function(category) {
		$('#wechatEmotion .categories').data('category', category);
		showFacePage(0);
		showPages();
	};

	var showFacePage = function(page) {

		var face;
		var html = '';
		var pageHtml = '';
		var rows = options.rows;
		var category = $('#wechatEmotion .categories').data('category');
		var faces = emotions[category];
		page = page || 0;
		if(faces && faces.length > 0){
			for (var i = page * rows, l = faces.length; i < l && i < (page + 1) * rows; ++i) {
				face = faces[i];
				var appendClass = "";
				if (face.icon.indexOf('.png')) {
					appendClass = 'shrink-wechat-spe';
				}
				html += '<li class="item"><a href="#" class="face"><img class="wechat-emotion '+appendClass+'" src="' + face.icon + '" alt="' + face.phrase + '" /></a></li>';
			}
		}
		$('#wechatEmotion .faces').html(html);
	};

	var showPages = function() {

		var html = '';
		var rows = options.rows;
		var category = $('#wechatEmotion .categories').data('category');
		var faces = emotions[category];
		if(faces && faces.length){
			var length = faces.length;
			if (length > rows) {
				for (var i = 0, l = Math.ceil(length / rows); i < l; ++i) {
					html += '<li class="item"><a href="#" class="page' + (i == 0 ? ' current' : '') + '">' + (i + 1) + '</a></li>';
				}
				$('#wechatEmotion .pages').html(html).show();
			} else {
				$('#wechatEmotion .pages').hide();
			}
		}
	};

	/**
	 * 为某个元素设置点击事件，点击弹出表情选择窗口
	 * @param  {[type]} target [description]
	 * @return {[type]}        [description]
	 */
	$.fn.wechatEmotion = function(target, editor) {
		if (editor) {
			$editor = editor;
		}
		target = target || function(){
			return $(this).parents('form').find('textarea,input[type=text]').eq(0);
		};

		var $that = $(this).last();
		var offset = $that.offset();
		if($that.is(':visible') || true){
			if(typeof target == 'function'){
				$target = target.call($that);
			}else{
				$target = $(target);
			}

			loadEmotions(function(){
				showCategory(defCategory);
				if(customEmojiData.length > 0){
					showCategory(emojiCategory);
				}
				showCatPage(0);
			});
			$('#wechatEmotion').css({
				bottom: 131,
				left: offset.left
			}).show();
		}

		return this;
	};

	$.fn.parseWechat = function() {

		if(! categories){
			parsingArray = $(this);
			loadEmotions();
		}else if(categories.length == 0){
			parsingArray = parsingArray.add($(this));
		}else{
			$(this).each(function() {
				var $this = $(this);
				var html = $this.html();

				var reg=new RegExp(wechatRegx,"gm");
				html = html.replace(wechatRegx, function($1) {
					var url = emotionsMap[$1];
					if (url) {
						return '<img class="wechat-emotion" src="' + url + '" alt="[表情]" />';
					}
					return $1;
				});

				$this.html(html);
			});
		}

		return this;
	};
	
	$.fn.parseWechat2 = function(html) {
		if(! categories){
			parsingArray = $(this);
			loadEmotions();
		}
		
		var reg=new RegExp(wechatRegx,"gm");
		var emotions = html.match(reg);
		if (!emotions || emotions.length < 1){
			return html;
		}
		
		for (var i = 0; i < emotions.length; i++) {
			html = html.replace(reg, function($1) {
				var appendClass = "";
				if (specialRegx.indexOf($1) >= 0) {
					appendClass = "shrink-wechat-spe";
				}
				var url = emotionsMap[$1];
				if (url) {
					return '<img class="wechat-emotion '+ appendClass +'" src="' + url + '" alt="' + '[微信表情]' + '" />';
				}
				return $1;
			});
		}
		
		for (var i = 0; i < emotions.length; i++) {
			html = html.replace("[微信表情]",emotions[i]);
		}
		
		return html;
	};


	$.fn.insertTextWechat = function(text) {
		//mobile send emotion immediately
		var sendText = '<img class="wechat-emotion" src="' + emotionsMap[text] + '" alt="' + text + '" />';
		doSend(sendText);
		return;
		
		var url = emotionsMap[text];
		if (url) {
			this[0].innerHTML=this[0].innerHTML+'<img class="wechat-emotion" src="' + url + '" alt="' + text + '" />';
		}else{
			this[0].innerHTML=this[0].innerHTML+text;
		}
		//$(this[0]).val($(this[0]).val() + text);
		return this;
	}
	
	// 插入到editor
	$.fn.insertWechatEditor = function(text) {
		var url = emotionsMap[text];
		var appendClass = "";
		if (specialRegx.indexOf(text) >= 0) {
			appendClass = "shrink-wechat-spe";
		}
		if (url) {
			$editor.insertHtml('<img class="wechat-emotion '+appendClass+'" style="width:auto; max-width:auto; height: 24px;" src="' + url + '" alt="' + text + '" />');
		}else{
			$editor.insertHtml(text);
		}
		$editor.focus();
		return this;
	}
	
	$.fn.getWechatEmotionHtml = function(text) {
		var url = emotionsMap[text];
		var appendClass = "";
		if (specialRegx.indexOf(text) >= 0) {
			appendClass = "shrink-wechat-spe";
		}
		var wechatHtml = "";
		if (url) {
			wechatHtml = '<img class="wechat-emotion jiaxin-emotion '+appendClass+'" style="width:auto; max-width:auto; height: 24px;" src="' + url + '" alt="' + text + '" />';
		}
		return wechatHtml;
	};

	$.fn.wechatEmotion.options = {
		rows: 36,				// 每页显示的表情数
		language: 'cnname',		// 简体（cnname）、繁体（twname）
		appKey: '1362404091'	// 新浪微博开放平台的应用ID
	};
})(jQuery);
